package com.mkjb.service.impl;

import com.mkjb.dto.ChangePasswordDto;
import com.mkjb.dto.UserFormDto;
import com.mkjb.dto.UserListDto;
import com.mkjb.entity.User;
import com.mkjb.repository.UserMapper;
import com.mkjb.service.UserService;
import com.mkjb.utils.SessionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by DingJie on 2017/3/31.
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByName(String name) {
        return userMapper.findByName(name);
    }

    @Override
    public void getList(UserListDto listDto) {
        List<User> list = userMapper.getList(listDto);
        listDto.addAllList(list);
    }

    @Override
    public UserFormDto loadUserFromDto(String uuid) {
        if (StringUtils.isNotBlank(uuid)) {
            User byUuid = userMapper.findByUuid(uuid);
            return new UserFormDto(byUuid);
        }
        return new UserFormDto();
    }

    @Override
    public void edit(UserFormDto formDto) {
        if (StringUtils.isNotBlank(formDto.getUuid())) {
            User byUuid = userMapper.findByUuid(formDto.getUuid());
            formDto.update(byUuid);
            userMapper.update(byUuid);
        }
        User user = new User();
        formDto.update(user);
        userMapper.save(user);
    }

    @Override
    public void delete(String uuid) {
        userMapper.delete(uuid);
    }

    @Override
    public void editChangePassword(ChangePasswordDto formDto) {
        User user = (User)SessionUtils.getCurrentUserAccount();
        user.setPassword(formDto.getNewPassword());
        userMapper.update(user);
    }
}
